﻿using System;
using System.Collections.Generic;
using System.Web;
using Barbar.MapReport.DataSource.Facade;
using Barbar.MapReport.Common;
using Barbar.MapReport.DataSource.Query;

public class ContactRegionGroup : ContactCollection {
  private SimpleRegion m_Region;

  public SimpleRegion Region {
    get { return m_Region; }
  }

  private ContactRegionGroup(SimpleRegion region) {
    m_Region = region;
  }

  public static SortedList<string, ContactRegionGroup> CreateContactRegionGroups() {
    SortedList<string, ContactRegionGroup> result = new SortedList<string, ContactRegionGroup>();

    IDataSourceService service = new DataSourceService();
    foreach (Contact contact in DataProvider.Instance.Contacts) {
      if (!contact.Latitude.HasValue || !contact.Longitude.HasValue)
        continue;
      GeoPoint point = new GeoPoint(contact.Latitude.Value, contact.Longitude.Value);
      RegionRequestQuery query = new RegionRequestQuery();
      query.Criteria = new RegionContainsPoint(point);
      MultipleRegionResponse response = (MultipleRegionResponse)service.GetRegions(query);
      if (response.Regions != null && response.Regions.Count > 0) {
        // we just take the first and ignore rest, query should specify region level or parent
        SimpleRegion region = response.Regions[0];
        ContactRegionGroup group = null;
        if (!result.TryGetValue(region.Id, out group)) {
          group = new ContactRegionGroup(region);
          result.Add(region.Id, group);
        }
        group.Add(contact);
      }
    }

    return result;
  }
}
